package com.wenc.psi.fgmt.homefgmt;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;

import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.table.TableData;
import com.wenc.psi.R;
import com.wenc.psi.bean.SaleBean;
import com.wenc.psi.bean.SaleDetailBean;
import com.wenc.psi.databinding.FragmentSaleBinding;
import com.wenc.psi.pojo.Sale;
import com.wenc.psi.pojo.SaleDetail;
import com.wenc.psi.vmd.PersonViewModel;
import com.wenc.psi.vmd.SaleOrderViewModel;
import com.wenc.psi.vmd.SaleViewModel;

import java.util.LinkedList;
import java.util.List;

public class SaleFragment extends Fragment {

    private FragmentSaleBinding binding;
    private SaleViewModel saleViewModel;
    private SaleOrderViewModel saleOrderViewModel;
    private static final String[] discounts;
    private static final String[] paymentMethod;
    private PartFragment partFragment;
    private ChoiceCustomerFragment choiceCustomerFragment;
    Column<Integer> column1;
    Column<String> column2;
    Column<String> column3;
    Column<Double> column4;
    Column<Integer> column5;

    static {
        discounts = new String[]{"1.00", "0.98", "0.95", "0.9", "0.85", "0.8"};
        paymentMethod = new String[]{"请选择", "现金","银行","挂账", "微信", "支付宝"};
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 获取DataBinding
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_sale, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 构造partFragment
        partFragment = new PartFragment();
        // 构造customerFragment
        choiceCustomerFragment = new ChoiceCustomerFragment();
        // 初始化控件
        initView();
        // 初始化smartTable
        initTable();
        // 获取saleViewModel
        saleViewModel = new ViewModelProvider(getActivity()).get(SaleViewModel.class);
        // 初始化数据
        saleViewModel.initSale();
        // 设置经手人
        saleViewModel.setEmployee(new ViewModelProvider(getActivity()).get(PersonViewModel.class).getEmployeeLive().getValue().getName(),
                new ViewModelProvider(getActivity()).get(PersonViewModel.class).getEmployeeLive().getValue().getId());
        // 对SaleBean进行监听
        saleViewModel.getSaleDetailLive().observe(getActivity(), saleDetailBeans -> {
            System.out.println("有变化，我是salefragment");
            refreshData(saleDetailBeans);
        });
        // 绑定数据
        binding.setData(saleViewModel);
        binding.setLifecycleOwner(this);
        // 获取saleOrderViewModel
        saleOrderViewModel = new ViewModelProvider(getActivity()).get(SaleOrderViewModel.class);
    }

    // 初始化smartTable
    private void initTable() {
        column1 = new Column<Integer>("序号", "serialNumber");
        column2 = new Column<String>("编号", "partId");
        column3 = new Column<String>("配件", "partName");
        column4 = new Column<Double>("单价", "price");
        column5 = new Column<Integer>("数量", "quantity");
        binding.saleDetailTable.getConfig().setShowXSequence(false);
        binding.saleDetailTable.getConfig().setShowYSequence(false);
    }

    // 初始化控件
    private void initView() {
        // 设置折扣spinner
        binding.saleDiscount.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, discounts));
        binding.saleDiscount.setSelection(0, true);
        binding.saleDiscount.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                saleViewModel.setDiscount(Double.valueOf(parent.getSelectedItem().toString()));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        // 设置额外费用
        binding.saleAddition.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {
                double addition;
                if (s.toString().length() == 0) addition = 0.00;
                else addition = Double.parseDouble(s.toString());
                saleViewModel.setAddition(addition);
            }
        });
        // 设置付款状态
        binding.salePaymentStatus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String paymentStatus;
                if (isChecked) paymentStatus = "已付款";
                else paymentStatus = "未付款";
                saleViewModel.setPaymentStatus(paymentStatus);
            }
        });
        // 设置付款方法
        binding.salePaymentMethod.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, paymentMethod));
        binding.salePaymentMethod.setSelection(0, true);
        binding.salePaymentMethod.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                saleViewModel.setPaymentMethod(parent.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // 点击添加配件事件
        binding.btAddPart.setOnClickListener(v -> {
            System.out.println("添加配件");
            // 获取事务
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            if (!partFragment.isAdded())
                transaction.add(R.id.part_fragment_container, partFragment);
            // 显示fragment
            transaction.show(partFragment);
            transaction.commit();
        });
        // 点击选择客户事件
        binding.btSearchCustomer.setOnClickListener(v -> {
            System.out.println("选择客户");
            // 获取事务
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            if (!choiceCustomerFragment.isAdded())
                transaction.add(R.id.customer_fragment_container, choiceCustomerFragment);
            // 显示fragment
            transaction.show(choiceCustomerFragment);
            transaction.commit();
        });
        // 点击返回事件
        binding.titleBtBack.setOnClickListener((e) -> {
            Navigation.findNavController(getView()).navigateUp();
        });
        // 点击返回事件
        binding.saleBack.setOnClickListener((e) -> {
            Navigation.findNavController(getView()).navigateUp();
        });
        // 点击清除事件
        binding.saleClear.setOnClickListener((e) -> {

        });
        // 点击提交事件
        binding.saleCommit.setOnClickListener((e) -> {
            Sale sale = (Sale) saleViewModel.getSaleLive().getValue();
            SaleDetail[] saleDetails = saleViewModel.getSaleDetailLive().getValue().toArray(new SaleDetail[saleViewModel.getSaleDetailLive().getValue().size()]);
            saleOrderViewModel.inserSaleOrder(sale, saleDetails);
        });
    }

    // 刷新数据
    private void refreshData(List<SaleDetailBean> data) {
        TableData<SaleDetailBean> tableData = new TableData<SaleDetailBean>("单详情", data, column1, column2, column3, column4, column5);
        binding.saleDetailTable.setTableData(tableData);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 清除数据
        saleViewModel.close();
    }
}